package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author Wang Chengzhi
 * @create 2019-10-22 10:06
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置字符集
        request.setCharacterEncoding("utf-8");

        //2.获取验证码
        //2.1 获取用户输入的验证码
        String verifycode = request.getParameter("verifycode");
        //2.2 获取生成的验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        //3.判断验证码
        if (!checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码不正确
            //提示信息
            request.setAttribute("login_msg","验证码输入有误");

            //转发会login.jsp
            request.getRequestDispatcher("/index.jsp").forward(request,response);

            //直接结束方法
            return;

        }
        //4.获取用户名密码并判断
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            //封装user对象
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用service 的login方法判断
        UserService service = new UserServiceImpl();
        User loginUser = service.findUserByUsernameAndPassword(user);
        //5.返回
        if (loginUser != null){

            //登陆成功
            session.setAttribute("user",user);
            response.sendRedirect(request.getContextPath() +"/login.jsp");
        }else {
            //登陆失败
            //提示信息
            request.setAttribute("login_msg","用户名或密码输入有误");
            //转发
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
